<?php

class Service_similar extends MY_Service
{
    public function __construct()
    {
        parent::__construct();
        $this->load->library('HttpUtil');
        $this->load->config('common/url_info');
        $this->load->model('Model_urls');
    }

    public function index()
    {
        $index = (int)$this->getConfigValByKey("similar_index");
        $limit = (int)$this->getConfigValByKey("similar_limit");
        $sql = "select * from urls where ((HEX(title) REGEXP '^(..)*(E[4-9])' AND HEX(remark) REGEXP '^(..)*(E[4-9])') OR weight > 999) AND id > ? AND `status` = 0 AND `show` = 1 limit ?";
        $list = $this->Model_urls->query($sql, [$index, $limit]);
        if (empty($list)) {
            $this->updateConfigValByKey("similar_index", 0);
            return false;
        }

        $lastId = $index;
        foreach ($list as $url) {
            $this->_dealSimilar($url['url']);
            $lastId = $url['id'];
        }

        $nextIndex = $lastId;
        $this->updateConfigValByKey("similar_index", $nextIndex);
    }

    public function indexV2()
    {
        $index = (int)$this->getConfigValByKey("similar_index_v2");
        $limit = (int)$this->getConfigValByKey("similar_limit_v2");
        $sql = "select * from urls where ((HEX(title) REGEXP '^(..)*(E[4-9])' AND HEX(remark) REGEXP '^(..)*(E[4-9])') OR weight > 999) AND id > ? AND `status` = 0 AND `show` = 1 limit ?";
        $list = $this->Model_urls->query($sql, [$index, $limit]);
        if (empty($list)) {
            $this->updateConfigValByKey("similar_index_v2", 0);
            return false;
        }

        $lastId = $index;
        foreach ($list as $url) {
            $this->_dealSimilarV2($url['url']);
            $lastId = $url['id'];
        }

        $nextIndex = $lastId;
        $this->updateConfigValByKey("similar_index_v2", $nextIndex);
    }

    private function _dealSimilar($url)
    {
        $res = $this->_getSimilars($url);
        if (!isset($res['SimilarSites'])) {
            return;
        }

        foreach ($res['SimilarSites'] as $item) {
            $urlInfo = [
                'url' => "//" . trim($item['Site']),
                'title' => trim($item['Title']),
                'remark' => (isset($item['Description']) ? trim($item['Description']) : ''),
                'icon' => '',
                'icon_sina' => '',
                'show' => 0
            ];
            $this->Model_urls->insert($urlInfo);
        }
    }

    private function _getSimilars($url)
    {
        $site = $this->config->item('similar');
        $site['data'] = ['url' => $url];
        $res = HttpUtil::cfg_request_options($site);
        return json_decode($res, true);
    }

    private function _dealSimilarV2($url)
    {
        $res = $this->_getSimilarsV2($url);
        if (!isset($res['SimilarSites'])) {
            return;
        }

        foreach ($res['SimilarSites'] as $item) {
            // 限制前5名
            if ($item['SimilarityRank'] > (int)$this->getConfigValByKey("similar_rank_limit_v2")) {
                continue;
            }

            $urlInfo = [
                'url' => "//" . trim($item['Site']),
                'title' => '',
                'remark' => (isset($item['Description']) ? trim($item['Description']) : ''),
                'icon' => '',
                'icon_sina' => '',
                'show' => 0
            ];
            $list = $this->Model_urls->getList(1, ['url' => $urlInfo['url']]);
            if (empty($list)) {
                $this->Model_urls->insert($urlInfo);
            }
        }
    }

    private function _getSimilarsV2($url)
    {
        $site = $this->config->item('similar_v2');
        $arr = parse_url($url);
        $host = trim($arr['host'], 'www.');
        $site['url'] .= $host;
        $res = HttpUtil::cfg_request_options($site);
        return json_decode($res, true);
    }
}
